import router from ".";
import store from "../store";
import { Message } from "element-ui";
import { getToken } from "@/utils/auth";
import { urlWhiteList } from "@/config/consistant";
import defaultSettings from '@/config/settings'
import LoadingBar from "@/components/LoadingBar";

function getPageTitle(pageTitle){
  const title = defaultSettings.title || 'Web'
  if(pageTitle) {
    return `${pageTitle} - ${title}`
  }
  return `${title}`
}

function hasPermission(roles, permissionRoles) {
  if (roles.indexOf("admin") >= 0) return true;
  if (!permissionRoles) return true;
  return roles.some(role => permissionRoles.indexOf(role) >= 0);
}

const loadingBar = (status, url) => {
  if (!urlWhiteList.includes(url)) {
    if (status === "start") {
      LoadingBar.start();
    }
    if (status === "finish") {
      LoadingBar.finish();
    }
  }
};

router.beforeEach(async (to, from, next) => {

  document.title = getPageTitle(to.meta.title);

  if (getToken()) {

    loadingBar("start", to.path);

    if (to.path === "/login") {
      next({ path: "/dashboard" });
    } else {

      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        if ( hasPermission(store.getters.roles, to.meta.roles)) {
          next();
        } else {
          next({ path: "/401", replace: true, query: { noGoBack: true } });
        }
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch("user/getInfo");

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch("permission/generateRoutes", roles);

          // dynamically add accessible routes
          router.addRoutes(accessRoutes);

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true });
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next({path: '/login', query: {redirect: to.path}})
        }
      }
    }
  } else {
    if (urlWhiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next({path: '/login', query: {redirect: to.fullPath}})
    }
  }
});

router.afterEach(route => {
  loadingBar("finish", route.path);
});
